from __future__ import absolute_import
import time

from celery import shared_task
from cronmanger.celery import app

from .models import Supervisor_Process, SupervisorHost, Supervisor_Action_History

import logging

logger = logging.getLogger()


@app.task
def supervisor_processlist_status_update_task(ip=None, process_list=None):
    """ 更新进程列表 """
    if not isinstance(process_list, list):
        logger.error(f"supervisor_status_update_task {process_list},必须传入进程列表对象")
        return None

    supv_host_obj = SupervisorHost.objects.filter(ip=ip)
    if not supv_host_obj.exists():
        logger.error(f"supervisor_status_update_task {ip},操作对象不存在")
        return None

    supv_host_obj = supv_host_obj.first()
    qs = Supervisor_Process.objects.filter(ip=ip)
    qs.delete()

    tmp = []
    for process in process_list:
        process_name = process['name']
        s = Supervisor_Process(name=process_name, ip=ip, detail=process, supervisor_host=supv_host_obj)
        tmp.append(s)
    Supervisor_Process.objects.bulk_create(tmp)
    logger.info(f"supervisor_status_update_task {ip},刷新进程信息成功")


#
# @app.task
# def supervisor_process_status_update_task(ip=None, process=None):
#     """ 更新进程"""
#     if not isinstance(process, dict):
#         logger.error(f"supervisor_status_update_task {process},必须传入进程对象")
#         return None
#
#     supv_host_obj = SupervisorHost.objects.filter(ip=ip)
#     if not supv_host_obj.exists():
#         logger.error(f"supervisor_status_update_task {ip},操作对象不存在")
#         return None
#
#     supv_host_obj = supv_host_obj.first()
#     qs = Supervisor_Process.objects.filter(ip=ip)
#     qs.delete()
#
#     tmp = []
#     for process in process_list:
#         process_name = process['name']
#         s = Supervisor_Process(name=process_name, ip=ip, detail=process, supervisor_host=supv_host_obj)
#         tmp.append(s)
#     Supervisor_Process.objects.bulk_create(tmp)
#     logger.info(f"supervisor_status_update_task {ip},刷新进程信息成功")


@app.task
def write_msg_to_log_and_db_task(action_name=None, ip=None, process_name=None, status_code=None, user=None, msg=None):
    """
    记录操作历史
        :param action_name:
        :param ip:
        :param process_name:
        :param status_code:
        :param user:
        :param msg:
        :return:
    """
    msg_res = {
        "action_name": action_name,
        "ip": ip,
        "process_name": process_name,
        "status_code": status_code,
        "user": user,
        "desc": msg
    }

    if status_code == True:
        logger.info(msg_res)
    else:
        logger.error(msg_res)

    # 操作记录到数据库
    Supervisor_Action_History.objects.create(**msg_res)
    return msg_res


@shared_task
def flush_all_process_info_task():
    pass


class A_Test_Task(app.Task):
    def run(self, logsss, ):
        print("logsss")
        time.sleep(10)
        print("sleep 10")
        logger.info(f"输入的信息是:{logsss}")
